<?php

namespace app\common\model;

use think\Db;
use think\Model;

class CommissionRebate extends Model
{
    // 表名
    protected $name = 'commission_rebate';
	
	// 自动写入时间戳字段
	protected $autoWriteTimestamp = false;
	
	// 定义时间戳字段名
	protected $createTime = false;
	protected $updateTime = false;
	
	// 追加属性
	protected $append = [
		'superior_type_text',
		'agent_type_text',
		'rebate_type_text',
		'self_type_text'
	];
	
	const REBATE_TYPE_PDD = 1;
	const REBATE_TYPE_TBK = 2;
	const REBATE_TYPE_JD = 3;
	
	public static $rebateTypeList = [
		self::REBATE_TYPE_PDD => '拼多多',
		self::REBATE_TYPE_TBK => '淘宝客',
		self::REBATE_TYPE_JD => '京东'
	];
	
	public function getRebateTypeTextAttr($value, $data) {
		$value = $value ? $value : $data['rebate_type'];
		$list = self::$rebateTypeList;
		return isset($list[$value]) ? $list[$value] : '';
	}
	
	
	public function getSuperiorTypeList()
	{
		//1按比例,2固定金额
		return ['1' => __('按比例'),'2' => __('固定金额')];
	}
	
	public function getAgentTypeList()
	{
		return ['1' => __('按比例'),'2' => __('固定金额')];
	}
	
	
	public function getSuperiorTypeTextAttr($value, $data)
	{
		$value = $value ? $value : $data['superior_type'];
		$list = $this->getSuperiorTypeList();
		return isset($list[$value]) ? $list[$value] : '';
	}
	
	public function getSelfTypeTextAttr($value, $data)
	{
		$value = $value ? $value : $data['self_type'];
		$list = $this->getSuperiorTypeList();
		return isset($list[$value]) ? $list[$value] : '';
	}
	
	
	public function getAgentTypeTextAttr($value, $data)
	{
		$value = $value ? $value : $data['agent_type'];
		$list = $this->getAgentTypeList();
		return isset($list[$value]) ? $list[$value] : '';
	}
	
	
	/**
	 * 给相关人员返利
	 * @param $amount 佣金金额
	 * @param $userId 购买用户
	 * @param $config 返利配置
	 * @param $orderId 返昨记录ID
	 * @param $typeStr 优惠券类型文字
	 * @return bool
	 * @throws \think\Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function rebate($amount, $userId, $config, $orderId, $typeStr){
		//查找用户推荐人
		$recomments = Db::name('user')->field('id, parent_path, agent_user_id')->find($userId);
		$parent = [];
		if($recomments['parent_path']){
			$parents = array_reverse(explode(',', $recomments['parent_path']));
			$parent = [
				'pid' => isset($parents[0]) ? $parents[0] : '',
				'ppid' => isset($parents[1]) ? $parents[1] : '',
				'pppid' => isset($parents[2]) ? $parents[2] : '',
			];
		}
		
		$agentModel = new Agent();
		//查找用户代理
		$agents = [];
		if($recomments['agent_user_id']){
			$agent = Db::name('agent')->where(['user_id' => $recomments['agent_user_id']])->find();
			switch ($agent['level']) {
				case $agentModel::LEVEL_2:
					//普通代理
					$agents = [
						'aid' => $agent['user_id'],
						'aaid' => $agent['pid'],
						'aaaid' => $agent['ppid']
					];
					break;
				case $agentModel::LEVEL_3:
					$agents = [
						'aid' => $agent['user_id'],
						'aaid' => $agent['user_id'],
						'aaaid' => $agent['pid']
					];
					break;
				case $agentModel::LEVEL_4:
					$agents = [
						'aid' => $agent['user_id'],
						'aaid' => $agent['user_id'],
						'aaaid' => $agent['user_id']
					];
					break;
				default:;
			}
		}
		
		
		//计算推荐人佣金
		if($config['superior_type'] == 1) {
			//按比例算
			$parentAmount = [
				'pid' => floor($amount * $config['pid']*100)/100, //向下取整
				'ppid' => floor($amount * $config['ppid']*100)/100, //向下取整
				'pppid' => floor($amount * $config['pppid']*100)/100, //向下取整
			];
		} else {
			//按固定金额算
			$parentAmount = [
				'pid' => $config['pid'],
				'ppid' => $config['ppid'],
				'pppid' => $config['pppid'],
			];
		}
		
		//计算代理佣金
		if($config['agent_type'] == 1){
			//按比例算
			$agentAmount = [
				'aid' => floor($amount * $config['aid']*100)/100, //向下取整
				'aaid' => floor($amount * $config['aaid']*100)/100, //向下取整
				'aaaid' => floor($amount * $config['aaaid']*100)/100, //向下取整
			];
		} else {
			//按固定金额算
			$agentAmount = [
				'aid' => $config['aid'],
				'aaid' => $config['aaid'],
				'aaaid' => $config['aaaid'],
			];
		}
		
		//购买用户自己
		if($config['self_type'] == 1) {
			$selfAmount = floor($amount * $config['self']*100)/100;
		} else {
			$selfAmount = $config['self'];
		}
		
		if($selfAmount > 0) {
			$selfRes = $this->addAmountAndLog($userId, $selfAmount, $orderId, $typeStr.'订单返利', $userId);
			if(!$selfRes) {
				$this->error = $typeStr.'订单ID【'.$orderId.'】用户'.$this->error;
				return false;
			}
		}
		

		//一级推荐人
		if(isset($parent['pid']) && $parent['pid'] && $parentAmount['pid'] > 0){
			$pidRes = $this->addAmountAndLog($parent['pid'], $parentAmount['pid'], $orderId, $typeStr.'推广一级推荐人返利', $userId);
			if(!$pidRes) {
				$this->error = $typeStr.'订单ID【'.$orderId.'】一级推荐人'.$this->error;
				return false;
			}
		}
		
		//二级推荐人
		if(isset($parent['ppid']) && $parent['ppid'] && $parentAmount['ppid'] > 0){
			$ppidRes = $this->addAmountAndLog($parent['ppid'], $parentAmount['ppid'], $orderId, $typeStr.'推广二级推荐人返利', $userId);
			if(!$ppidRes) {
				$this->error = $typeStr.'订单ID【'.$orderId.'】二级推荐人'.$this->error;
				return false;
			}
		}
		
		//三级推荐人
		if(isset($parent['pppid']) && $parent['pppid'] && $parentAmount['pppid'] > 0){
			$pppidRes = $this->addAmountAndLog($parent['pppid'], $parentAmount['pppid'], $orderId, $typeStr.'推广三级推荐人返利', $userId);
			if(!$pppidRes) {
				$this->error = $typeStr.'订单ID【'.$orderId.'】三级推荐人'.$this->error;
				return false;
			}
		}
		
		//如果有代理商，且代理商返利费用大于0
		if($agents && ($agentAmount['aid'] > 0 || $agentAmount['aaid'] > 0 || $agentAmount['aaaid'] > 0)) {
			if($agents['aid'] == $agents['aaid'] && $agents['aid'] == $agents['aaaid']){
				//所属代理是高级代理商
				$amount = $agentAmount['aid'] + $agentAmount['aaid'] + $agentAmount['aaaid'];
				$allres = $this->addAmountAndLog($agents['aid'], $amount, $orderId, $typeStr.'直接代理为高级代理返利', $userId);
				if(!$allres) {
					$this->error = $typeStr.'订单ID【'.$orderId.'】直接代理为高级代理返利'.$this->error;
					return false;
				}
			} elseif ($agents['aid'] == $agents['aaid']){
				$aaAmount = $agentAmount['aid'] + $agentAmount['aaid'];
				if($aaAmount > 0){
					$aaRes = $this->addAmountAndLog($agents['aid'], $aaAmount, $orderId, $typeStr.'直接代理为中级代理返利', $userId);
					if(!$aaRes) {
						$this->error = $typeStr.'订单ID【'.$orderId.'】直接代理为中级代理返利'.$this->error;
						return false;
					}
				}
				
				if(!$agents['aaaid'] && $agentAmount['aaaid'] > 0){
					$aaaRes = $this->addAmountAndLog($agents['aaaid'], $agentAmount['aaaid'], $orderId, $typeStr.'高级代理返利', $userId);
					if(!$aaaRes) {
						$this->error = $typeStr.'订单ID【'.$orderId.'】高级代理返利'.$this->error;
						return false;
					}
				}
			} else {
				if($agents['aid'] && $agentAmount['aid'] > 0){
					$aRes = $this->addAmountAndLog($agents['aid'], $agentAmount['aid'], $orderId, $typeStr.'初级代理返利', $userId);
					if(!$aRes) {
						$this->error = $typeStr.'订单ID【'.$orderId.'】初级代理返利'.$this->error;
						return false;
					}
				}
				
				if($agents['aaid'] && $agentAmount['aaid'] > 0){
					$aaRes = $this->addAmountAndLog($agents['aaid'], $agentAmount['aaid'], $orderId, $typeStr.'中级代理返利', $userId);
					if(!$aaRes) {
						$this->error = $typeStr.'订单ID【'.$orderId.'】中级代理返利'.$this->error;
						return false;
					}
				}
				
				if($agents['aaaid'] && $agentAmount['aaaid'] > 0){
					$aaaRes = $this->addAmountAndLog($agents['aaaid'], $agentAmount['aaaid'], $orderId, $typeStr.'高级代理返利', $userId);
					if(!$aaaRes) {
						$this->error = $typeStr.'订单ID【'.$orderId.'】高级代理返利'.$this->error;
						return false;
					}
				}
			}
		}
		
		return true;
	}
	
	
	/**
	 * 给相关人员添加待返利记录
	 * @param $goodsId 商品ID
	 * @param $amount 佣金金额
	 * @param $userId 购买用户
	 * @param $config 返利配置
	 * @param $orderId 返昨记录ID
	 * @param $typeStr 优惠券类型文字
	 * @return bool
	 * @throws \think\Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function addRebateRocord($goodsId, $amount, $userId, $config, $orderId, $type, $typeStr){
		//查找用户推荐人
		$recomments = Db::name('user')->field('id, parent_path, agent_user_id')->find($userId);
		$parent = [];
		if($recomments['parent_path']){
			$parents = array_reverse(explode(',', $recomments['parent_path']));
			$parent = [
				'pid' => isset($parents[0]) ? $parents[0] : '',
				'ppid' => isset($parents[1]) ? $parents[1] : '',
				'pppid' => isset($parents[2]) ? $parents[2] : '',
			];
		}
		
		$agentModel = new Agent();
		//查找用户代理
		$agents = [];
		if($recomments['agent_user_id']){
			$agent = Db::name('agent')->where(['user_id' => $recomments['agent_user_id']])->find();
			switch ($agent['level']) {
				case $agentModel::LEVEL_2:
					//普通代理
					$agents = [
						'aid' => $agent['user_id'],
						'aaid' => $agent['pid'],
						'aaaid' => $agent['ppid']
					];
					break;
				case $agentModel::LEVEL_3:
					$agents = [
						'aid' => $agent['user_id'],
						'aaid' => $agent['user_id'],
						'aaaid' => $agent['pid']
					];
					break;
				case $agentModel::LEVEL_4:
					$agents = [
						'aid' => $agent['user_id'],
						'aaid' => $agent['user_id'],
						'aaaid' => $agent['user_id']
					];
					break;
				default:;
			}
		}
		
		
		//计算推荐人佣金
		if($config['superior_type'] == 1) {
			//按比例算
			$parentAmount = [
				'pid' => floor($amount * $config['pid']*100)/100, //向下取整
				'ppid' => floor($amount * $config['ppid']*100)/100, //向下取整
				'pppid' => floor($amount * $config['pppid']*100)/100, //向下取整
			];
		} else {
			//按固定金额算
			$parentAmount = [
				'pid' => $config['pid'],
				'ppid' => $config['ppid'],
				'pppid' => $config['pppid'],
			];
		}
		
		//计算代理佣金
		if($config['agent_type'] == 1){
			//按比例算
			$agentAmount = [
				'aid' => floor($amount * $config['aid']*100)/100, //向下取整
				'aaid' => floor($amount * $config['aaid']*100)/100, //向下取整
				'aaaid' => floor($amount * $config['aaaid']*100)/100, //向下取整
			];
		} else {
			//按固定金额算
			$agentAmount = [
				'aid' => $config['aid'],
				'aaid' => $config['aaid'],
				'aaaid' => $config['aaaid'],
			];
		}
		
		//购买用户自己
		if($config['self_type'] == 1) {
			$selfAmount = floor($amount * $config['self']*100)/100;
		} else {
			$selfAmount = $config['self'];
		}
		
		$recordModel = new RebateRecord();
		if($selfAmount > 0) {
			$selfRes = $recordModel->addRecord($selfAmount, $userId, $orderId, $type, $typeStr.'订单返利', $goodsId);
			
			if(!$selfRes) {
				$this->error = $typeStr.'订单ID【'.$orderId.'】用户'.$this->error;
				return false;
			}
		}
		
		
		//一级推荐人
		if(isset($parent['pid']) && $parent['pid'] && $parentAmount['pid'] > 0){
			$pidRes = $recordModel->addRecord($parentAmount['pid'], $parent['pid'], $orderId, $type, $typeStr.'推广一级推荐人返利', $goodsId);
			if(!$pidRes) {
				$this->error = $typeStr.'订单ID【'.$orderId.'】一级推荐人'.$this->error;
				return false;
			}
		}
		
		//二级推荐人
		if(isset($parent['ppid']) && $parent['ppid'] && $parentAmount['ppid'] > 0){
			$ppidRes = $recordModel->addRecord($parentAmount['ppid'], $parent['ppid'], $orderId, $type, $typeStr.'推广二级推荐人返利', $goodsId);
			if(!$ppidRes) {
				$this->error = $typeStr.'订单ID【'.$orderId.'】二级推荐人'.$this->error;
				return false;
			}
		}
		
		//三级推荐人
		if(isset($parent['pppid']) && $parent['pppid'] && $parentAmount['pppid'] > 0){
			$pppidRes = $recordModel->addRecord($parentAmount['pppid'], $parent['pppid'], $orderId,$type, $typeStr.'推广三级推荐人返利', $goodsId);
			if(!$pppidRes) {
				$this->error = $typeStr.'订单ID【'.$orderId.'】三级推荐人'.$this->error;
				return false;
			}
		}
		
		//如果有代理商，且代理商返利费用大于0
		if($agents && ($agentAmount['aid'] > 0 || $agentAmount['aaid'] > 0 || $agentAmount['aaaid'] > 0)) {
			if($agents['aid'] == $agents['aaid'] && $agents['aid'] == $agents['aaaid']){
				//所属代理是高级代理商
				$amount = $agentAmount['aid'] + $agentAmount['aaid'] + $agentAmount['aaaid'];
				$allres = $recordModel->addRecord($amount, $agents['aid'], $orderId, $type, $typeStr.'直接代理为高级代理返利', $goodsId);
				if(!$allres) {
					$this->error = $typeStr.'订单ID【'.$orderId.'】直接代理为高级代理返利'.$this->error;
					return false;
				}
			} elseif ($agents['aid'] == $agents['aaid']){
				$aaAmount = $agentAmount['aid'] + $agentAmount['aaid'];
				if($aaAmount > 0){
					$aaRes = $recordModel->addRecord($aaAmount, $agents['aid'], $orderId, $type, $typeStr.'直接代理为中级代理返利', $goodsId);
					if(!$aaRes) {
						$this->error = $typeStr.'订单ID【'.$orderId.'】直接代理为中级代理返利'.$this->error;
						return false;
					}
				}
				
				if($agents['aaaid'] && $agentAmount['aaaid'] > 0){
					$aaaRes = $recordModel->addRecord($agentAmount['aaaid'], $agents['aaaid'], $orderId, $type, $typeStr.'高级代理返利', $goodsId);
					if(!$aaaRes) {
						$this->error = $typeStr.'订单ID【'.$orderId.'】高级代理返利'.$this->error;
						return false;
					}
				}
			} else {
				if($agents['aid'] && $agentAmount['aid'] > 0){
					$aRes = $recordModel->addRecord($agentAmount['aid'], $agents['aid'], $orderId, $type, $typeStr.'初级代理返利', $goodsId);
					if(!$aRes) {
						$this->error = $typeStr.'订单ID【'.$orderId.'】初级代理返利'.$this->error;
						return false;
					}
				}
				
				if($agents['aaid'] && $agentAmount['aaid'] > 0){
					$aaRes = $recordModel->addRecord($agentAmount['aaid'], $agents['aaid'], $orderId, $type, $typeStr.'中级代理返利', $goodsId);
					if(!$aaRes) {
						$this->error = $typeStr.'订单ID【'.$orderId.'】中级代理返利'.$this->error;
						return false;
					}
				}
				
				if($agents['aaaid'] && $agentAmount['aaaid'] > 0){
					$aaaRes = $recordModel->addRecord($agentAmount['aaaid'], $agents['aaaid'], $orderId, $type, $typeStr.'高级代理返利', $goodsId);
					if(!$aaaRes) {
						$this->error = $typeStr.'订单ID【'.$orderId.'】高级代理返利'.$this->error;
						return false;
					}
				}
			}
		}
		
		return true;
	}
	
	/**
	 * 添加金额和流水
	 * @param $userId 用户ID
	 * @param $amount 金额
	 * @param string $orderId 佣金订单ID
	 * @param string $remark 备注
	 * @param $relationId 相关用户
	 * @return bool
	 * @throws \think\Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	protected function addAmountAndLog($userId, $amount, $orderId = '', $remark = '', $relationId){
		$user = Db::name('user')->find($userId);
		
		//不是正常用户不返利
		if($user['status'] != \app\admin\model\User::STATUS_Y){
			return true;
		}
		
		$userRes = Db::name('user')
			->where(['id' => $userId])
			->setInc('balance', $amount);
		
		if(!$userRes){
			$this->error = '添加用户【'.$userId.'】金额出错';
			return false;
		}
		
		$logModel = new FundsRecord();
		$logRes = $logModel->addRecord($userId, $amount, $user['balance'], $logModel::ACCOUNT_TYPE_BALANCE, $logModel::OPE_TYPE_PLUS, $logModel::TYPE_VOUCHER_REBATE, $orderId, $remark, $relationId);
		if(!$logRes){
			$this->error = '添加用户【'.$userId.'】流水出错';
			return false;
		}
		
		return true;
	}
	
	
	
	
	
	
}
